package com.lucky.interceptor;

import com.lucky.annotation.Authority;
import com.lucky.pojo.vo.User;
import com.lucky.util.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 权限验证拦截器
 * @Author Jalyson
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/6/26
 */
public class AuthorityInterceptor implements HandlerInterceptor {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            //检查权限
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Authority authority = method.getAnnotation(Authority.class);
            if (authority != null && authority.permission() == false) {
                // 如果注解不为null, 并指定说明不需要权限, 直接放过
                LOGGER.info("AuthorityInterceptor 检查到Authority注解，标注该方法无需权限校验");
                return true;
            }

            //检查登录token
            String token = httpServletRequest.getSession().getId();

            User user = (User) RedisCache.getData(token);
            if (user == null) {
                token = httpServletRequest.getHeader("Authorization");
                user = (User) RedisCache.getData(token);
                if(user == null){
                    //未登录，跳到登录界面
                    LOGGER.info("AuthorityInterceptor 检查到未登录系统，强制跳转到登录页面");
                    httpServletResponse.sendRedirect("/login");
                }

            }

            // 以后每次操作时从request中获取session，从session中获取用户信息
            // 然后根据用户信息从数据库中查权限信息
            /*if (authority != null && authority.role() != null) {
                if (!StringUtils.isEmpty(user.getRole())) {
                    String[] userRole = user.getRole().split(",");
                    List<String> auths = Arrays.asList(userRole);
                    String[] roles = authority.role();
                    if (checkRole(auths, roles)) {
                        return true;
                    }
                    LOGGER.info("AuthorityInterceptor 检查到用户({})权限不足({})",user.getRole(),roles);
                }
                httpServletResponse.setCharacterEncoding("utf-8");
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                PrintWriter out = httpServletResponse.getWriter();
                out.print("{\"msg\":\"权限不足\"}");
                out.flush();
                out.close();
                return false;
            }*/
        }
        return true;
    }

    /**
     * 检查用户是否包含所要求的所有权限
     *
     * @param auths 用户role
     * @param roles 要求的role
     * @return
     */
    private boolean checkRole(List<String> auths, String[] roles) {
        boolean isContain = true;
        for (String role : roles) {
            if (!auths.contains(role)) {
                isContain = false;
            }
        }
        return isContain;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

